package com.maven.zh.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.maven.zh.bean.Datas;
import com.maven.zh.bean.Manager;
import com.maven.zh.bean.Page;
import com.maven.zh.bean.Role;
import com.maven.zh.service.ManagerService;
import com.maven.zh.service.RoleService;
import com.maven.zh.util.Const;

/**
 * 管理员的控制层
 * @author
 * 
 */
@Controller
@RequestMapping("/manager")
public class ManagerController {

	@Autowired
	private ManagerService managerService;
	
	@Autowired
	private RoleService roleService;
	
	/**
	 * 管理员登录
	 * @param rememberme
	 * @param manager
	 * @param resp
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/dologin")
	public Object dologin(String yzm,String rememberme,Manager manager, HttpServletResponse resp ,HttpSession session){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//从session中取出验证码
		String code = (String)session.getAttribute("code");
		if(yzm.equals(code)){
			//验证码输入正确
			Manager dbmanager = managerService.queryManager4Login(manager);
			//验证
			if(dbmanager==null){
				//查询的用户为空
				session.setAttribute("msg", "用户名或密码输入错误，请重新输入。");
				resultMap.put("success",false);
			}else{
				session.setAttribute(Const.SESSION_MANAGER, dbmanager);
				//登录成功后验证是否记住密码
				if("1".equals( rememberme ) ){
					//生成cookie，保存当前的用户账号和密码
					String logincode = "loginacct="+manager.getLoginacct()+"&userpswd="+manager.getUserpswd();
					Cookie c = new Cookie("logincode", logincode);
					c.setMaxAge(60*60*24*14);
					c.setPath("/");
					resp.addCookie(c);
				}
				resultMap.put("success",true);
			}
		}else{
			//验证码输入错误
			session.setAttribute("msg", "验证码输入错误，请重新输入。");
			resultMap.put("success",false);
		}
		return resultMap;
	}
	/**
	 * 跳转到用户列表页面
	 * @return
	 */
	@RequestMapping("/list")
	public String list(HttpSession session) {
		//查询登录的用户信息
		Manager loginManager = (Manager)session.getAttribute(Const.SESSION_MANAGER);
		
		if(loginManager==null){
			
			return "login";
		}else{
			return "manager/list";
		}
		
	}
	/**
	 * 批量删除用户的方法
	 * @param ds
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/doDeletes")
	public Object doDeletes(Datas ds){
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		try {
			managerService.deleteBatManagers(ds);
			resultMap.put("success", true);
		} catch ( Exception e ) {
			e.printStackTrace();
			resultMap.put("success", false);
		}
		
		return resultMap;
	}
	
	/**
	 * 删除选中的用户
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public Object delete(Integer id){
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		try {
			int count = managerService.deleteManagerById(id);
			resultMap.put("success", count==1);
		} catch ( Exception e ) {
			e.printStackTrace();
			resultMap.put("success", false);
		}
		
		return resultMap;
	}
	/**
	 * 分页查询用户信息
	 * @param qname 检索时的用户名
	 * @param pageno  当前页
	 * @param pagesize 每页显示的条数
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/queryPageManagers")
	public Object queryPageManagers(String qname, Integer pageno, @RequestParam(defaultValue="1",required=false)Integer pagesize){
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//获取分页对象
		Page<Manager> managerPage = managerService.queryPage(pageno, pagesize, qname);
		
		if(managerPage.getDatas().size()!=0){
			managerPage.setPageno(pageno);
			managerPage.setPagesize(pagesize);
			resultMap.put("managerPage", managerPage);
			resultMap.put("success", true);	
		}else{
			
			resultMap.put("success", false);
		}
		return resultMap;
	}
	
	/**
	 * 跳转都用户修改页面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/edit")
	public String edit( Integer id, Model model ) {
		
		// 根据主键查询用户信息
		Manager manager = managerService.queryManagerById(id);
		model.addAttribute("manager", manager);
		
		return "manager/edit";
	}
	
	/**
	 * 修改用户数据
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/update")
	public Object update( Manager manager ) {
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		try {
			int result = managerService.updateManager(manager);
			resultMap.put("success", result==1);
		} catch ( Exception e ) {
			e.printStackTrace();
			resultMap.put("success", false);
		}
		
		return resultMap;
	}
	
	/**
	 * 跳转到用户新增页面
	 * @return
	 */
	@RequestMapping("/add")
	public String add() {
		return "manager/add";
	}
	
	/**
	 * 新增用户数据
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/insert")
	public Object insert( Manager manager ) {
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		try {
		
			// 获取当前的系统时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateString = sdf.format(new Date());
			manager.setCreatetime(dateString);
			
			managerService.insertManager(manager);
			
			resultMap.put("success", true);
		} catch ( Exception e ) {
			e.printStackTrace();
			resultMap.put("success", false);
		}
		
		return resultMap;
	}
	/**
	 * 跳转到分配角色的页面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/auth/{id}")
	public String auth( @PathVariable("id")Integer id, Model model ) {
		
		// 查询所有的角色数据
		List<Role> roles = roleService.queryAll();
		
		// 获取未分配的角色数据和已分配的角色数据
		List<Role> unassignList = new ArrayList<Role>();
		List<Role> assignList = new ArrayList<Role>();
		
		// 查询用户分配的角色数据
		List<Integer> roleids = managerService.queryRoleIdsByManagerId(id);
		
		for ( Role role : roles ) {
			if ( roleids.contains(role.getId()) ) {
				assignList.add(role);
			} else {
				unassignList.add(role);
			}
		}
		
		model.addAttribute("unassignList", unassignList);
		model.addAttribute("assignList", assignList);
		
		model.addAttribute("managerid", id);
		
		return "manager/auth";
	}
	
	/**
	 * 分配管理员角色的方法
	 * @param managerid
	 * @param ds
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/assignRole")
	public Object assignRole(Integer managerid,Datas ds){
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		try {
			managerService.assignRoles(managerid, ds);
			resultMap.put("success", true);
		} catch ( Exception e ) {
			e.printStackTrace();
			resultMap.put("success", false);
		}
		
		return resultMap;
	}
	
	/**
	 * 取消管理员分配的角色
	 * @param ds
	 * @param managerid
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/cancleAssignRole")
	public Object cancleAssignRole( Datas ds, Integer managerid ) {
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		try {
			managerService.cancleAssignRoles(managerid, ds);
			resultMap.put("success", true);
		} catch ( Exception e ) {
			e.printStackTrace();
			resultMap.put("success", false);
		}
		
		return resultMap;
	}
	
	

}
